package com.fengmi.security;

import cn.hutool.json.JSONUtil;
import com.fengmi.entity.SysUser;
import com.fengmi.utils.JwtUtils;
import com.fengmi.utils.RsaUtils;
import com.fengmi.vo.ResultVO;
import io.jsonwebtoken.JwtException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/*
 * @Author 123
 * @Date 2022/2/9 20:41
 * @Version 1.0
 */

public class MyBasicAuthenticationFilter extends BasicAuthenticationFilter {
    public MyBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            // 因该过滤器在前面，所以要前放行login
            String requestURI = request.getRequestURI();

            if ("/user/login".equals(requestURI)) {
                // 放行
                chain.doFilter(request, response);
                // 必须加return
                return;
            }

            if ("/user/verify".equals(requestURI)) {
                // 放行
                chain.doFilter(request, response);
                // 必须加return
                return;
            }
            // 从请求头中获取jwt令牌 约定key为token
            String token = request.getHeader("token");

            if (StringUtils.isEmpty(token)) {
                // 直接拦截，响应给客户端
                response(response, new ResultVO(false, "令牌不能为空"));
            }
            // token不为空，利用公钥解密token获取用户信息
            // 获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa_pub").getPath());
            // 解密token
            SysUser info = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);
            // 获取用户的authorities
            String authority = info.getRoles() + "," + info.getPermissions();
            // 利用工具类获取
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authority);

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(info, null, authorities);

            // 将用户的信息放到spring security的上下文中
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

            // 放行
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof JwtException) {
                response(response, new ResultVO(false, "无效令牌!!!"));
            } else {
                response(response, new ResultVO(false, "其他异常！！！！"));
            }
        }
    }

    private void response(HttpServletResponse response, ResultVO res) {
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter out = response.getWriter();

            out.write(JSONUtil.toJsonPrettyStr(res));
            out.flush();
            out.close();
        } catch (Exception e) {

        }
    }
}

